package com.zx.framework.socket;

import org.apache.log4j.Logger;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;

/**
 * 启动socketio服务
 * 2015-09-28
 * @author stylewolf
 * 
 * @since 4.2
 */
public abstract class ServerAdapter{
	
	private static final Logger LOGGER = Logger.getLogger(ServerAdapter.class);
	
	protected SocketIOServer socketIOServer;

	/**
	 * 获取服务器的配置 地址 端口等
	 * @return
	 */
	protected abstract Configuration configuration();
	
	public <T> void addEventListener(String eventName, Class<T> eventClass, DataListener<T> listener){
		socketIOServer.addEventListener(eventName, eventClass, listener);
	}

	public void onStartup(){
		socketIOServer = new SocketIOServer(configuration());
		socketIOServer.addConnectListener(connectListener());
		socketIOServer.addDisconnectListener(disconnectListener());
		socketIOServer.addEventListener("test", Object.class, new IoDataListener<Object>());
		socketIOServer.start();
	}
	/**
	 * 连接监听
	 * @return
	 */
	public ConnectListener connectListener(){
		return new IoConnectListener();
	}
	public DisconnectListener disconnectListener(){
		return new IoDisconnectListener();
	}
	/**
	 * 连接监听器
	 * @author stylewolf
	 *
	 */
	public class IoConnectListener implements ConnectListener{

		@Override
		public void onConnect(SocketIOClient client) {
			if(LOGGER.isDebugEnabled()){
				LOGGER.debug(client);
			}
		}
		
	}
	/**
	 * 连接断开监听器
	 * @author stylewolf
	 *
	 */
	public class IoDisconnectListener implements DisconnectListener{

		@Override
		public void onDisconnect(SocketIOClient client) {
			if(LOGGER.isDebugEnabled()){
				LOGGER.debug(client);
			}
		}
	}
}
